package com.liss.lissaiagent.app;


import com.liss.lissaiagent.advisor.MyLoggerAdvistor;
import com.liss.lissaiagent.chatmemory.FileBasedChatMemory;

import com.liss.lissaiagent.rag.LoveAppRagCustomAdvisorFactory;
import com.liss.lissaiagent.rag.QueryWriter;
import com.liss.lissaiagent.tool.PDFGenerationTool;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;

import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Component;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

/**
 * @Author: Mr.Li
 * @CreateTime: 2025-10-10
 * @Description: 恋爱大师app
 * @Version: 1.0
 */
@Component
@Slf4j
public class LoveApp {

    private final ChatClient chatClient;

    //系统预设
    private static final String SYSTEM_PROMPT = "扮演深耕恋爱心理领域的专家。开场向用户表明身份，告知用户可倾诉恋爱难题。" +
            "围绕单身、恋爱、已婚三种状态提问：单身状态询问社交圈拓展及追求心仪对象的困扰；" +
            "恋爱状态询问沟通、习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。" +
            "引导用户详述事情经过、对方反应及自身想法，以便给出专属解决方案。";

    public LoveApp(ChatModel dashscopeChatModel) {
        //初始化基于文件的对话记忆
        String fileDir =  System.getProperty("user.dir") + "/tmp/chat-memory";
        FileBasedChatMemory chatMemory = new FileBasedChatMemory(fileDir);
        //初始化基于内存的对话记忆
//        ChatMemory chatMemory = new InMemoryChatMemory();
        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory)
                        //使用自定义的日志advisor
//                        new MyLoggerAdvistor()
                )
                .build();
    }


    public String doChat(String message,String chatId){
        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content:{}",content);
        return content;
    }


//    新建一个LoveReport类
    record LoveReport(String title, List<String> suggestions){}

    /**
     * @description: 测试结构化输出
     * @param message
	 * @param chatId
     * @return com.liss.lissaiagent.app.LoveApp.LoveReport
     * @author Mr.Li
     * @date 2025/10/10
     **/
    public LoveReport doChatWithReport(String message,String chatId){
        LoveReport result = chatClient.prompt()
                .system(SYSTEM_PROMPT + "每次对话后都要生成恋爱结果，标题为{用户名}的恋爱报告，内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                /*格式化输出*/
                .entity(LoveReport.class);
        log.info("loveReport:{}",result);
        return result;
    }


    //实现RAG检索增强

    @Resource
    private Advisor loveAppRagCloudAdvisor;

    @Resource
    private VectorStore loveAppVectorStore;

    @Resource
    private VectorStore pgVectorStore;

    //引入查询重写器
    @Resource
    private QueryWriter queryWriter;

    public String doChatWithRag(String message,String chatId){

        //调用查写重写
        String queriedWriter = queryWriter.queryWriter(message);

        ChatResponse chatResponse = chatClient.prompt()
                //使用查写后的prompt
                .user(queriedWriter)
//                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new MyLoggerAdvistor())
                //使用用户顾问工厂
//                .advisors(LoveAppRagCustomAdvisorFactory.createLoveAppRagCustomAdvisor(loveAppVectorStore))
                //开启RAG检索-基于内存
//                .advisors(new QuestionAnswerAdvisor(loveAppVectorStore))
                //开启Rag检索-云知识库
                .advisors(loveAppRagCloudAdvisor)
                //基于pgVectore数据库的向量数据库
//                .advisors(new QuestionAnswerAdvisor(pgVectorStore))
                //工具调用
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content:{}",content);
        return content;
    }

    //调用工具
    @Resource
    private ToolCallback[] allTools;

    public String doChatWithTools(String message, String chatId) {
        ChatResponse chatResponse = chatClient
                .prompt()
//                .tools(new PDFGenerationTool())
                .tools(allTools)
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
//        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    //调用mcp

    @Resource
    private ToolCallbackProvider toolCallbackProvider;

    public String doChatWithMCP(String message, String chatId) {
        ChatResponse chatResponse = chatClient.prompt()
                .tools(toolCallbackProvider)
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new MyLoggerAdvistor())
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("MCP content: {}", content);
        return content;
    }
}
